package idv.arthur.work;

import java.io.IOException;
import java.io.StringReader;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.stream.JsonReader;

/**
 * Servlet implementation class SaveMRItems
 */
//@WebServlet(description = "將目前測試項目的結果回寫入計畫案", urlPatterns = { "/SaveMRItems" })
public class SaveMRItems extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SaveMRItems() {
        super();
    }

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 解析JSON數據，首先要創建一個JsonReader對象
		request.setCharacterEncoding("UTF-8");
		String jsonData = request.getParameter("sub_CDB");
		JsonReader reader = new JsonReader(new StringReader(jsonData));
		Widgets wid = new Widgets();
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		String strSQL = "";
		String returnResult = "";
		String mrid = "";
		String programmerName = "";
		String programmerContent = "";
		int tpid = Integer.parseInt(request.getParameter("tpid"));
		int isTCaccepted = 0;
		int isTCreviewed = 0;
		int isTCsubmitAble = 0;
		int isTCsubmitted = 0;
		int isTRaccepted = 0;
		int isTRreviewed = 0;
		int isTRsubmitAble = 0;
		int isTRsubmitted = 0;
		int isImportAble = 0;
		int isReviewer = 0;
		try {
			conn = wid.getConn(true);
			
			reader.beginArray();
			while (reader.hasNext()) {
				String module ="";
				String mrdescription = "";
				String createdate = "";
				String onlinedate = "";
				String sourceid = "";
				String isMail = "";
				String mrno = "";
				String process = "";
				String yymm ="";
				String description = "";
				String isFromImport = ""; 
				String fromXML = "";
				
				reader.beginObject();
				while (reader.hasNext()) {
					String tagName = reader.nextName();
					System.out.println("現在的tag是："+tagName);
					
					if ("reference".equalsIgnoreCase(tagName)||"designpm".equalsIgnoreCase(tagName) ||"propose".equalsIgnoreCase(tagName) ||"designer".equalsIgnoreCase(tagName)||"tester".equalsIgnoreCase(tagName)) {
						wid.deleteOwner(tpid, mrid, tagName, conn, ps, rs);
						reader.beginArray();
						while (reader.hasNext()) {
							if ("designpm".equalsIgnoreCase(tagName) ||"propose".equalsIgnoreCase(tagName) ||"designer".equalsIgnoreCase(tagName)||"tester".equalsIgnoreCase(tagName)) {
								reader.beginObject();
								System.out.println("reader.nextName()："+reader.nextName());
								wid.insertOwner(tpid, mrid, tagName, reader.nextString(), conn, ps, rs);
								reader.nextName();
								reader.skipValue();
								reader.endObject();
							} else {
								wid.insertOwner(tpid, mrid, tagName, reader.nextString(), conn, ps, rs);
							}
						}
						reader.endArray();
					} else if ("programmer".equalsIgnoreCase(tagName)) {
						reader.beginArray();
						while (reader.hasNext()) {
							reader.beginObject();
							while (reader.hasNext()) {
								String tagName3 = reader.nextName();
								if ("name".equalsIgnoreCase(tagName3)) {
									programmerName = reader.nextString(); 
								} else {
									programmerContent = reader.nextString();
								}
							}
							reader.endObject();

							wid.deleteOwner(tpid, mrid, "programmer", conn, ps, rs);
							
							strSQL = "INSERT INTO activiti.tms_mritem_"+tagName+ "(tpid, mrid, userID,content) VALUES (?,?,?,?)";
							ps = conn.prepareStatement(strSQL);
							ps.setInt(1, tpid);
							ps.setString(2, mrid);
							ps.setString(3, programmerName);
							ps.setString(4, programmerContent);
							ps.execute();
						}
						reader.endArray();
					} else if ("require".equalsIgnoreCase(tagName)) {
						wid.deleteOwner(tpid, mrid, tagName, conn, ps, rs);
						
						reader.beginArray();
						while (reader.hasNext()) {
							String requireID ="";
							String swdsID ="";
							String sitrID ="";
							
							reader.beginObject();
							while (reader.hasNext()) {
								String tagName3 = reader.nextName();
								if ("requireID".equalsIgnoreCase(tagName3)) {
									requireID = reader.nextString(); 
								} else if ("swdsID".equalsIgnoreCase(tagName3)) {
									swdsID = reader.nextString();
								} else {
									sitrID = reader.nextString();
								}
							}
							strSQL = "INSERT INTO activiti.tms_mritem_requirelog(tpid, mrid,reqLogID,swdsID,sitrID) VALUES (?,?,?,?,?)";
							ps = conn.prepareStatement(strSQL);
							ps.setInt(1, tpid);
							ps.setString(2, mrid);
							ps.setString(3, requireID);
							ps.setString(4, swdsID);
							ps.setString(5, sitrID);
							ps.execute();
							
							reader.endObject();
						}
						reader.endArray();
					} else if("testResult".equalsIgnoreCase(tagName)) {
						reader.skipValue();
					} else {
						if ("isSelected".equalsIgnoreCase(tagName)) {
							reader.nextBoolean();
						} else if ("isFromImport".equalsIgnoreCase(tagName) ) {
							isFromImport = String.valueOf(reader.nextBoolean());
						} else if ("isTCaccepted".equalsIgnoreCase(tagName)){
							isTCaccepted= reader.nextBoolean()?1:0;
						} else if ("isTCreviewed".equalsIgnoreCase(tagName)){
							isTCreviewed=reader.nextBoolean()?1:0;
						} else if ("isTCsubmitAble".equalsIgnoreCase(tagName)){
							isTCsubmitAble=reader.nextBoolean()?1:0;
						} else if ("isTCsubmitted".equalsIgnoreCase(tagName)){
							isTCsubmitted=reader.nextBoolean()?1:0;
						} else if ("isTRaccepted".equalsIgnoreCase(tagName)){
							isTRaccepted=reader.nextBoolean()?1:0;
						} else if ("isTRreviewed".equalsIgnoreCase(tagName)){
							isTRreviewed=reader.nextBoolean()?1:0;
						} else if ("isTRsubmitAble".equalsIgnoreCase(tagName)){
							isTRsubmitAble=reader.nextBoolean()?1:0;
						} else if ("isTRsubmitted".equalsIgnoreCase(tagName)){
							isTRsubmitted=reader.nextBoolean()?1:0;
						} else if ("isImportAble".equalsIgnoreCase(tagName)){
							isImportAble = reader.nextBoolean()?1:0;
						} else if ("isReviewer".equalsIgnoreCase(tagName)){
							isReviewer = reader.nextBoolean()?1:0;
						} else {
							String cont = reader.nextString();
							
							if ("fromXML".equalsIgnoreCase(tagName)) {
								fromXML = cont;	 
							} else if ("desc".equalsIgnoreCase(tagName)) {
								description = cont;
							} else if ("yymm".equalsIgnoreCase(tagName)) {
								yymm = cont;
							} else if ("module".equalsIgnoreCase(tagName)) {
								module = cont;
							} else if ("mrdescription".equalsIgnoreCase(tagName)) {
								mrdescription = cont;
							} else if ("createdate".equalsIgnoreCase(tagName)) {
								createdate = cont;
							} else if ("onlinedate".equalsIgnoreCase(tagName)) {
								onlinedate = cont;
							} else if ("sourceid".equalsIgnoreCase(tagName)) {
								sourceid = cont;
							} else if ("isMail".equalsIgnoreCase(tagName)) {
								isMail = cont;
							} else if ("mrno".equalsIgnoreCase(tagName)) {
								mrno = cont;
							} else if ("process".equalsIgnoreCase(tagName)) {
								process = cont;
							} else if ("mrid".equalsIgnoreCase(tagName)) {
								mrid = cont;
							}
						}
					}
				}
				reader.endObject();
				
				strSQL = "SELECT tpid FROM activiti.tms_tpitem WHERE tpid =? AND mrid = ?";
				ps = conn.prepareStatement(strSQL);
				ps.setInt(1, tpid);
				ps.setString(2, mrid);
				rs = ps.executeQuery();
				
				if ( rs.next() ){
					strSQL = "UPDATE tms_tpitem SET tpid=?,mrid=?,module=?,mrdescription=?,onlinedate=?,sourceid=?,isMail=?,mrno=?,process=?,yymm=?,description=?,lastUpdatedDate=? WHERE tpid=? AND mrid=?";
					ps = conn.prepareStatement(strSQL);
					ps.setInt(1, tpid);
					ps.setString(2, mrid);
					ps.setString(3, module);
					ps.setString(4, mrdescription);
					ps.setString(5, onlinedate);
					ps.setString(6, sourceid);
					ps.setString(7, isMail);
					ps.setString(8, mrno);
					ps.setString(9, process);
					ps.setString(10, yymm);
					ps.setString(11, description);
					ps.setTimestamp(12, wid.currentTimeStamp());
					ps.setInt(13, tpid);
					ps.setString(14, mrid);
					ps.executeUpdate();
				} else {
					strSQL = "INSERT INTO activiti.tms_tpitem (tpid, mrid, module, mrdescription, createdate, onlinedate, sourceid, isMail, mrno, process, yymm, description, isFromImport, fromXML, isTCsubmitAble, isTCsubmitted, isTCreviewed, isTRsubmitAble, isTRsubmitted, isTRreviewed, createdDate, lastUpdatedDate) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
					ps = conn.prepareStatement(strSQL);
					ps.setInt(1, tpid);
					ps.setString(2, mrid);
					ps.setString(3, module);
					ps.setString(4, mrdescription);
					ps.setString(5, createdate);
					ps.setString(6, onlinedate);
					ps.setString(7, sourceid);
					ps.setString(8, isMail);
					ps.setString(9, mrno);
					ps.setString(10, process);
					ps.setString(11, yymm);
					ps.setString(12, description);
					ps.setString(13, isFromImport);
					ps.setString(14, fromXML);
					ps.setInt(15,isTCsubmitAble);
					ps.setInt(16,isTCsubmitted);
					ps.setInt(17,isTCreviewed);
					ps.setInt(18,isTRsubmitAble);
					ps.setInt(19,isTRsubmitted);
					ps.setInt(20,isTRreviewed);
					ps.setTimestamp(21, wid.currentTimeStamp());
					ps.setTimestamp(22, wid.currentTimeStamp());
					ps.execute();
				}
			}
			reader.endArray();
			returnResult = "OK";
		} catch (IOException e) {
			returnResult = wid.keepErrorMes(conn, ps, e, "", true);
		} catch (SQLException e) {
			returnResult = wid.keepErrorMes(conn, ps, e, "", true);
		} finally {
			try {
				if (rs!= null) {rs.close();}
				if (ps!= null) {ps.close();}
				if (conn!= null) {conn.close();}
			} catch (SQLException e) {
				returnResult = "Error";
			}
		}
		
		response.setContentType("application/text");
		response.getWriter().write(returnResult);
	}
}
